using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CodeStory.WebControls
{
	internal class ValidateImageContainer : WebControl
	{
		private ValidateImage owner;

		public ValidateImageContainer(ValidateImage validateImage) {
			this.owner = validateImage;
		}

		public ValidateImage Owner {
			get { return owner; }
		}

		protected override void Render(HtmlTextWriter writer) {
			RenderContents(writer);
		}

		Control image;
		internal Control Image {
			get {
				if (image == null) {
					image = FindRequiredControl<Image>("Image");
				}
				return image;
			}
		}


		Control userInputTextBox;
		internal Control UserInputTextBox {
			get {
				if (userInputTextBox == null) {
					userInputTextBox = FindRequiredControl<IEditableTextControl>("UserInput");
				}
				return userInputTextBox;
			}
		}

		Control hidden;

		internal Control HiddenControl {
			get {
				if (hidden == null) {
					hidden = FindRequiredControl<HtmlControl>("Hidden");
				}
				return hidden;
			}
		}
		#region Find Control
		protected Control FindOptionalControl<RequiredType>(string id) {
			return this.FindControl<RequiredType>(id, false);
		}

		protected Control FindRequiredControl<RequiredType>(string id) {
			return this.FindControl<RequiredType>(id, true);
		}

		private Control FindControl<RequiredType>(string id, bool required) {
			return FindControl<RequiredType>(id, required, string.Empty);
		}

		private Control FindControl<RequiredType>(string id, bool required, string errorMsg) {
			Control control = this.FindControl(id);
			if (control is RequiredType) {
				return control;
			}
			if (required && !this.Owner.InternalDesignMode) {
				throw new HttpException(errorMsg);
			}
			return null;
		}
		#endregion
	}
}